package gold.github.CloudCenter.provider;

import com.alibaba.fastjson.JSON;
import gold.github.CloudCenter.dto.WxDTO;
import gold.github.CloudCenter.utils.JwtUtil;
import gold.github.CloudCenter.utils.RedisUtil;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: XYBH
 * @Description:
 * @Date: Created in 2020/4/25 0025 23:21
 * @Modified:
 */
@Component
public class WxProvider {
    @Autowired
    private RedisUtil redisUtil;

    public WxDTO getWxDTO(String code) {
//        OkHttpClient client = new OkHttpClient();
//        Request request = new Request.Builder()
//                .url("https://api.weixin.qq.com/sns/jscode2session?appid=wxf51927709d0a3fd2&secret=3eb3eafc2278d8e02f995c8193fed89c&js_code=" + code + "&grant_type=authorization_code")
//                .build();
//        try {
//            Response response = client.newCall(request).execute();
//            String string = response.body() != null ? response.body().string() : null;
//            return JSON.parseObject(string, WxDTO.class);
//        } catch (IOException ignore) {
//        }
        return null;
    }

    public String getToken(String code) {
        Map<String, Object> claims = new HashMap<>();
        WxDTO wxDTO = getWxDTO(code);
        if (wxDTO == null) {
            return null;
        }
        claims.put("openId", wxDTO.getOpenId());
        claims.put("session_key", wxDTO.getSessionKey());
        String token = JwtUtil.generate(claims);
        redisUtil.set(token, wxDTO.getOpenId() + "::" + wxDTO.getSessionKey(), 0);
        redisUtil.expire(token, 60 * 60, 0);
        return token;
    }
}
